const mongodb = require('mongodb');
const ObjectId = mongodb.ObjectId;
const fs = require('fs');
const join = require('path').join;
const axios = require('axios');
const jsdom = require('jsdom');
const {JSDOM} = jsdom;
const jquery = require('jquery');
const _ = require('lodash');
const mongoskin = require('mongoskin');
const helper = mongoskin.helper;
/**
 *  填充ObjectID
 * @param obj 待填充的对象或者对象集合
 */
const fillObjectID = (obj) => {
    if (obj instanceof Array) {
        for (let i = 0; i < obj.length; i++) {
            obj[i]._id = new ObjectID();
        }
    } else if (obj instanceof Object) {
        obj._id = new ObjectID();
    } else {
        throw("参数错误!");
    }
    return obj;
};

const isObjectID = (idStr) => {
    return helper.isObjectID(idStr);
};

const toObjectId = (origin) => {
    if (origin instanceof Array) {
        let result = [];
        for (let i = 0; i < origin.length; i++) {
            result.push(new ObjectId(origin[i]))
        }
        return result
    } else if (origin instanceof String) {
        return new ObjectId(origin)
    } else {
        throw("参数错误!");
    }
};

/**
 *  查找目录下的文件
 * @param startPath  起始目录文件夹路径
 * @returns {Array}
 */
const findFileSync = (startPath) => {
    let result = [];

    const finder = function (path) {
        let files = fs.readdirSync(path);
        files.forEach((val, index) => {
            let fPath = join(path, val);
            let stats = fs.statSync(fPath);
            if (stats.isDirectory()) {
                finder(fPath)
            }
            else if (stats.isFile()) {
                result.push(fPath)
            }
        });
    };
    finder(startPath);
    return result;
};

/**
 * 从美团获取城市数据
 * @param city
 * @returns {Promise<any>}
 */
const getCityData = async (city) => {

    const url = "http://i.meituan.com/" + city;

    return new Promise((resolve, reject) => {
        axios.get(url).then((response) => {
            const {window} = new JSDOM(response.data);
            const $ = jquery(window);
            const datas = JSON.parse($('#filterData').text().trim());
            const BizAreaList = datas['BizAreaList'];
            const SubwayList = datas['SubwayList'];
            const areas = [];
            const subways = [];

            // 解析区域
            _(BizAreaList).forEach((item) => {
                let area = {
                    name: item['name'],
                    shopAreas: [],
                };
                _(item['subareas']).forEach((subarea) => {
                    area.shopAreas.push(subarea['name']);
                });
                areas.push(area);
            });
            // 解析地铁
            _(SubwayList).forEach((item) => {
                let subway = {
                    name: item['name'],
                    stations: [],
                };
                _(item['stations']).forEach((station) => {
                    subway.stations.push(station['name']);
                });
                subways.push(subway);
            });
            resolve({
                subways: subways,
                areas: areas
            })
        });
    });
};

module.exports = {
    fillObjectID, isObjectID, toObjectId, findFileSync, getCityData
};
